<template>
  <div class="upload">
    <el-card class="mycard">
      <h1>员工导入</h1>
      <upload :before-upload="beforeUpload" :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import { batchEmployee } from '@/api/employees'
export default {
  methods: {
    beforeUpload(file) {
      //   console.log(file)
      const less2M = file.size / 1024 / 1024 < 2
      if (!less2M) {
        this.$message.error('文件大小大于2m')
      }
      return less2M
    },
    formDate(days) {
      const time = new Date((days - 1) * 24 * 60 * 60 * 1000)
      time.setYear(time.getFullYear() - 70)
      return time
    },
    async onSuccess({ results }) {
      //   console.log(results)
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      // const Newrr=[]
      const newArr = results.map(item => {
        //   console.log;
        const newData = {}
        Object.keys(item).forEach(subitem => {
          if (
            obj[subitem] === 'timeOfEntry' ||
            obj[subitem] === 'correctionTime'
          ) {
            newData[obj[subitem]] = this.formDate(item[subitem])
          } else {
            newData[obj[subitem]] = item[subitem]
          }
        })
        return newData
      })
      //   console.log(newArr)
      await batchEmployee(newArr)
      this.$message.success('批量导入数据成功')
      this.$router.push('/employees')
    }
  }
}
</script>

<style lang="scss" scopend>
.upload {
  .mycard {
    padding: 20px;
    h1 {
      text-align: center;
    }
  }
}
</style>
